from fastapiApp.models.admin import User_Mo  # 导入User模型
from fastapiApp.schemas.user_schemas import *
from fastapi.exceptions import HTTPException
from datetime import datetime

class UserController(User_Mo):
    def __init__(self):
        self.model = User_Mo

    # 判断name是否已经存在
    async def is_exist(self, obj_in : UserCreate) -> int:
        if await self.model.filter(username=obj_in.username).exists():
            raise HTTPException(status_code=400, detail="用户名已存在")
        if await self.model.filter(email=obj_in.email).exists():
            raise HTTPException(status_code=400, detail="邮箱已被注册")
        return 0

    async def create_user(self, obj_in: UserCreate) -> None:
        # obj_in.password = get_password_hash(password=obj_in.password)
        await self.model.create(** obj_in.model_dump())
        return None

    # 修改用户信息
    async def update_user(self, obj_in:UserUpdate) -> None:
        user = await self.model.get(id=obj_in.id)
        user.username = obj_in.username
        user.password = obj_in.password
        user.email = obj_in.email
        user.is_active = obj_in.is_active
        user.is_superuser = obj_in.is_superuser
        user.roles_id = obj_in.roles_id
        user.dept_id = obj_in.dept_id
        await user.save()

    # 重置密码
    async def reset_password(self,user_id:int):
        user = await self.model.get(id = user_id)
        user.password = "123456"
        await user.save()

    # 写入最新的登录时间
    async def update_last_login(self, user_id: int) -> None:
        user = await self.model.get(id = user_id)
        user.last_login = datetime.now()
        await user.save()

    # 验证用户名及密码
    async def authenticate(self, credentials: CredentialsSchema) -> Optional["User_Mo"]:
        user = await self.model.filter(username=credentials.username).first()
        if not user:
            raise HTTPException(status_code=401, detail="无效的用户名")
        if credentials.password != user.password:
            raise HTTPException(status_code=401, detail="密码错误!")
        if not user.is_active:
            raise HTTPException(status_code=401, detail="用户已被禁用")
        return user

    # 查看用户list
    async def list(self, page: int, page_size: int, username: str, email: str, dept_id: int = None):
        if dept_id == None:
            query = await self.model.filter(username__icontains = username,email__icontains = email).offset((page - 1) * page_size).limit(page_size)
            count = await self.model.filter(username__icontains = username,email__icontains = email).count()
        else:
            query = await self.model.filter(username__icontains = username,email__icontains = email,dept_id__icontains = dept_id).offset((page - 1) * page_size).limit(page_size)
            count = await self.model.filter(username__icontains = username,email__icontains = email,dept_id__icontains = dept_id).count()
        data_list = [
            await role.to_dict()
            for role in query
        ]
        return count,data_list

user_controller = UserController()

GL_DependAuth = []

def creat_GL_DependAuth(username,access_token):
    global GL_DependAuth
    for item in GL_DependAuth:
        if item["username"] == username:
            item["access_token"] = access_token
            return
    GL_DependAuth.append({"username":username,"access_token":access_token})

def get_username_token(access_token):
    global GL_DependAuth
    for item in GL_DependAuth:
        if item["access_token"] == access_token:
            return item["username"]
    return None
